package com.xthink.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xthink.common.pojo.cards.CardPackage;
import com.xthink.common.pojo.cards.Cards;
import com.xthink.common.pojo.iPackage.Package;
import com.xthink.common.pojo.customer.Customer;
import com.xthink.common.pojo.polo.GroupTotal;
import com.xthink.common.pojo.polo.PoolGroup;
import com.xthink.common.result.AjaxResult;
import com.xthink.common.vo.pool.GroupTotalListVo;
import com.xthink.common.vo.pool.InsertGroupTotalVo;
import com.xthink.web.mapper.*;
import com.xthink.web.service.GroupTotalService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GroupTotalServiceImpl extends ServiceImpl<GroupTotalMapper, GroupTotal> implements GroupTotalService {

    @Autowired
    private GroupTotalMapper groupTotalMapper;

    @Autowired
    private CardsMapper cardsMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private CardPackageMapper cardPackageMapper;

    @Autowired
    private PackageMapper packageMapper;

    @Autowired
    private PoolGroupMapper poolGroupMapper;

    //池成员分页查询及搜索
    @Override
    public AjaxResult groupTotalList(GroupTotalListVo groupTotalListVo) {

        Page<GroupTotal> groupTotalPage = new Page<>(groupTotalListVo.getPage(), groupTotalListVo.getSize());

        LambdaQueryWrapper<GroupTotal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!StringUtils.isNotBlank(
                        groupTotalListVo.getCustomerName())
                , GroupTotal::getCustomerName
                , groupTotalListVo.getCustomerName());

        wrapper.between(
                StringUtils.isNotBlank(groupTotalListVo.getStartIccId()) || StringUtils.isNotBlank(groupTotalListVo.getEndIccId())
                , GroupTotal::getIccId
                , groupTotalListVo.getStartIccId()
                , groupTotalListVo.getEndIccId()
        );

        wrapper.eq(StringUtils.isNotBlank(groupTotalListVo.getGroupName())
                , GroupTotal::getGroupName
                , groupTotalListVo.getGroupName());


        wrapper.eq(GroupTotal::getPoolId, groupTotalListVo.getPoolId());

        Page<GroupTotal> groupTotalPage1 = groupTotalMapper.selectPage(groupTotalPage, wrapper);
        List<GroupTotal> records = groupTotalPage1.getRecords();

        return AjaxResult.success(records);
    }

    //绑定池卡片&&添加到流量池中&&添加进流量池小组
    @Override
    public AjaxResult insertGroupTotal(InsertGroupTotalVo insertGroupTotalVo) {

        if (!StringUtils.isNotBlank(insertGroupTotalVo.getGroupName())) {
            return AjaxResult.error("请选择池内小组");
        }

        Integer[] ids = insertGroupTotalVo.getIds();
        for (Integer id : ids) {
            GroupTotal groupTotal = new GroupTotal();
            LambdaUpdateWrapper<Cards> cardsWrapper = new LambdaUpdateWrapper<>();
            cardsWrapper.eq(Cards::getId, id).set(Cards::getPoolId, insertGroupTotalVo.getPoolId());
            int update = cardsMapper.update(null, cardsWrapper);
            if (update == 0) {
                return AjaxResult.error("卡片ID:" + id + "添加进流量池中失败");
            }
            //查找对应卡片信息
            Cards cards = cardsMapper.selectById(id);
            //查找客户信息
            Integer customerId = cards.getCustomerId();
            Customer customer = customerMapper.selectById(customerId);
            //存入客户名称(获取) iccid 卡号 池内小组名称 流量用量 所属流量池
            groupTotal.setCustomerName(customer.getCustomerName());
            groupTotal.setIccId(cards.getIccId());
            groupTotal.setCardNumber(cards.getCardNumber());
            groupTotal.setGroupName(insertGroupTotalVo.getGroupName());
            groupTotal.setConsumption(cards.getConsumption());
            groupTotal.setPoolId(insertGroupTotalVo.getPoolId());
            //获取流量限制额度
            LambdaUpdateWrapper<CardPackage> cardPackageWrapper = new LambdaUpdateWrapper<>();
            cardPackageWrapper.eq(CardPackage::getCardId, id);
            List<CardPackage> cardPackages = cardPackageMapper.selectList(cardPackageWrapper);
            Double quota = 0.00;
            for (CardPackage cardPackage : cardPackages) {
                Integer packageId = cardPackage.getPackageId();
                Package aPackage = packageMapper.selectById(packageId);
                Double packageSize = aPackage.getPackageSize();
                quota = packageSize + quota;
            }
            //set流量限制额度
            groupTotal.setQuota(quota);
            //添加进池成员
            int insert = groupTotalMapper.insert(groupTotal);
            if (insert == 0) {
                AjaxResult.error("卡片ID:" + id + "添加进" + insertGroupTotalVo.getGroupName() + "中失败");
            }
            //添加一次 对应的池小组卡数增加一张
            //先查询小组中目前卡数
            PoolGroup poolGroup = poolGroupMapper.selectById(insertGroupTotalVo.getGroupId());
            Integer cNumber = poolGroup.getCNumber();
            //查询目前小组流量使用额度
            Double groupQuota = poolGroup.getQuota();
            LambdaUpdateWrapper<PoolGroup> poolGroupWrapper = new LambdaUpdateWrapper<>();
            poolGroupWrapper.eq(PoolGroup::getId, insertGroupTotalVo.getGroupId())
                    //修改小组卡片数量
                    .set(PoolGroup::getCNumber, cNumber + 1)
                    //修改小组流量额度
                    .set(PoolGroup::getQuota, groupQuota + quota);
            //提交修改
            poolGroupMapper.update(null, poolGroupWrapper);
        }
        //获取该小组现有成员数
        QueryWrapper<GroupTotal> groupTotalWrapper = new QueryWrapper<>();
        groupTotalWrapper.eq("customer_name", insertGroupTotalVo.getGroupName())
                .select("DISTINCT customer_name");
        Integer pNumber = groupTotalMapper.selectCount(groupTotalWrapper);
        //修改小组现有成员数
        LambdaUpdateWrapper<PoolGroup> poolGroupWrapper = new LambdaUpdateWrapper<>();
        poolGroupWrapper.eq(PoolGroup::getId, insertGroupTotalVo.getGroupId())
                .set(PoolGroup::getPNumber, pNumber);
        //提交修改
        poolGroupMapper.update(null, poolGroupWrapper);
        return AjaxResult.success();
    }

    //解绑池卡片
    @Override
    public AjaxResult deleteGroupTotal(Integer[] ids) {

        for (Integer id : ids) {
            //通过ID获取卡片ICCID
            Cards cards = cardsMapper.selectById(id);
            String iccId = cards.getIccId();
            LambdaQueryWrapper<GroupTotal> groupTotalWrapper = new LambdaQueryWrapper<>();
            groupTotalWrapper.eq(GroupTotal::getIccId, iccId);
            GroupTotal groupTotal = groupTotalMapper.selectOne(groupTotalWrapper);
            //获取属于哪个小组 小组名称 流量用量 流量限额
            String groupName = groupTotal.getGroupName();
            Double consumption = cards.getConsumption();
            //查找对应小组的ID
            LambdaQueryWrapper<PoolGroup> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PoolGroup::getGroupName, groupName);
            PoolGroup poolGroup = poolGroupMapper.selectOne(wrapper);
            //获取流量限制额度
            LambdaUpdateWrapper<CardPackage> cardPackageWrapper = new LambdaUpdateWrapper<>();
            cardPackageWrapper.eq(CardPackage::getCardId, id);
            List<CardPackage> cardPackages = cardPackageMapper.selectList(cardPackageWrapper);
            Double quota = 0.00;
            for (CardPackage cardPackage : cardPackages) {
                Integer packageId = cardPackage.getPackageId();
                Package aPackage = packageMapper.selectById(packageId);
                Double packageSize = aPackage.getPackageSize();
                quota = packageSize + quota;
            }
            //对应的小组 卡片减 1 客户数量减 1 使用流量减掉 小组额度减掉
            //先查询小组中目前卡数
            Integer cNumber = poolGroup.getCNumber();
            //查询目前小组使用流量
            Double groupConsumption = poolGroup.getGroupConsumption();
            //查询目前小组流量额度
            Double groupQuota = poolGroup.getQuota();
            LambdaUpdateWrapper<PoolGroup> poolGroupWrapper = new LambdaUpdateWrapper<>();
            poolGroupWrapper.eq(PoolGroup::getId, poolGroup.getId())
                    //修改对应小组中卡片数量
                    .set(PoolGroup::getCNumber, cNumber - 1)
                    //修改对应小组中使用流量
                    .set(PoolGroup::getGroupConsumption, groupConsumption - consumption)
                    //修改对应小组中流量额度
                    .set(PoolGroup::getQuota, groupQuota - quota);
            poolGroupMapper.update(null, poolGroupWrapper);
            //修改卡片所属流量池 解绑就不再属于流量池中的卡片
            LambdaUpdateWrapper<Cards> cardsWrapper = new LambdaUpdateWrapper<>();
            cardsWrapper.eq(Cards::getId, id).set(Cards::getPoolId, 0);
            //修改卡片所属分组 改为"--" 不属于任何一个分组
            /*LambdaUpdateWrapper<GroupTotal> groupTotalLambdaUpdateWrapper2 = new LambdaUpdateWrapper<>();
            groupTotalLambdaUpdateWrapper2.eq(GroupTotal::getId, groupTotal.getId()).set(GroupTotal::getGroupName, "--");*/
            //提交修改
            cardsMapper.update(null, cardsWrapper);
            groupTotalMapper.deleteById(groupTotal.getId());
            //获取该小组现有成员数
            QueryWrapper<GroupTotal> groupTotalWrapper2 = new QueryWrapper<>();
            groupTotalWrapper2.eq("group_name", groupName)
                    .select("DISTINCT customer_name");
            Integer pNumber = groupTotalMapper.selectCount(groupTotalWrapper2);
            //修改小组现有成员数
            //如果跟之前成员数不相同则修改 相同则不修改
            Integer pNumber1 = poolGroup.getPNumber();
            if (!pNumber.equals(pNumber1)) {
                LambdaUpdateWrapper<PoolGroup> poolGroupWrapper2 = new LambdaUpdateWrapper<>();
                poolGroupWrapper2.eq(PoolGroup::getId, poolGroup.getId())
                        .set(PoolGroup::getPNumber, pNumber);
                //提交修改
                poolGroupMapper.update(null, poolGroupWrapper2);
            }
            //此成员不再属于任何一个流量池 所属流量池字段为0
            LambdaUpdateWrapper<GroupTotal> groupTotalLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            groupTotalLambdaUpdateWrapper.eq(GroupTotal::getId, groupTotal.getId())
                    .set(GroupTotal::getPoolId, 0);
            groupTotalMapper.update(null, groupTotalLambdaUpdateWrapper);
        }
        return AjaxResult.success();
    }

    //调拨小组卡片回显
    @Override
    public AjaxResult listCards(Integer[] ids) {

        ArrayList<Cards> cards = new ArrayList<>();
        for (Integer id : ids) {
            GroupTotal groupTotal = groupTotalMapper.selectById(id);
            //获取ICCID去卡片管理页面查卡片详情
            String iccId = groupTotal.getIccId();
            //创建卡片管理的wrapper
            LambdaQueryWrapper<Cards> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Cards::getIccId, iccId);
            Cards card = cardsMapper.selectOne(wrapper);
            cards.add(card);
        }
        return AjaxResult.success(cards);
    }

    //调拨小组卡片
    @Override
    public AjaxResult updateGroupTotal(Integer[] ids, Integer groupId) {
        //获取调拨到哪个小组
        PoolGroup poolGroupInsert = poolGroupMapper.selectById(groupId);
        //获取小组名称
        String groupNameInsert = poolGroupInsert.getGroupName();

        //调拨出去
        for (Integer id : ids) {
            //获取池成员 和 池成员对应的数据
            GroupTotal groupTotal = groupTotalMapper.selectById(id);
            //获取从哪个小组名称调拨出去
            String groupNameOut = groupTotal.getGroupName();
            //调拨出去的小组则扣掉卡片数量和流量额度和流量用量以及小组成员数
            //先找到对应的小组对象
            LambdaQueryWrapper<PoolGroup> wrapper = new LambdaQueryWrapper<>();
            //根据名称查找对应的小组
            wrapper.eq(PoolGroup::getGroupName, groupNameOut);
            //这是对应的小组
            PoolGroup poolGroupOut = poolGroupMapper.selectOne(wrapper);
            //对应小组当前的卡片数量减去调拨的数量
            LambdaUpdateWrapper<PoolGroup> poolGroupUpdateWrapper = new LambdaUpdateWrapper<>();
            poolGroupUpdateWrapper.eq(PoolGroup::getId, poolGroupOut.getId())
                    //修改卡片数量
                    .set(PoolGroup::getCNumber, poolGroupOut.getCNumber() - 1)
                    //修改小组使用流量
                    .set(PoolGroup::getGroupConsumption, poolGroupOut.getGroupConsumption() - groupTotal.getConsumption())
                    //修改小组额度
                    .set(PoolGroup::getQuota, poolGroupOut.getQuota() - groupTotal.getQuota());
            //修改该池成员小组名称 修改为调拨的小组名称
            LambdaUpdateWrapper<GroupTotal> groupTotalUpdateWrapper = new LambdaUpdateWrapper<>();
            groupTotalUpdateWrapper.eq(GroupTotal::getId, id).set(GroupTotal::getGroupName, groupNameInsert);

            //提交修改
            poolGroupMapper.update(null, poolGroupUpdateWrapper);
            groupTotalMapper.update(null, groupTotalUpdateWrapper);

            //当前池成员不属于该小组了 再去查询客户数量
            //获取该小组现有成员数
            QueryWrapper<GroupTotal> groupTotalWrapper2 = new QueryWrapper<>();
            groupTotalWrapper2.eq("group_name", groupNameOut)
                    .select("DISTINCT customer_name");
            Integer pNumber = groupTotalMapper.selectCount(groupTotalWrapper2);
            //修改小组现有成员数
            //如果跟之前成员数不相同则修改 相同则不修改
            Integer pNumber1 = poolGroupOut.getPNumber();
            if (!pNumber.equals(pNumber1)) {
                LambdaUpdateWrapper<PoolGroup> poolGroupWrapper2 = new LambdaUpdateWrapper<>();
                poolGroupWrapper2.eq(PoolGroup::getId, poolGroupOut.getPoolId())
                        .set(PoolGroup::getPNumber, pNumber);
                //提交修改
                poolGroupMapper.update(null, poolGroupWrapper2);
            }
        }


        //插入进调拨对应的小组
        for (Integer id : ids) {
            //获取池成员 和 池成员对应的数据
            GroupTotal groupTotal = groupTotalMapper.selectById(id);
            //调拨到对应小组增加客户 卡片 流量使用 流量额度
            LambdaUpdateWrapper<PoolGroup> poolGroupUpdateWrapper = new LambdaUpdateWrapper<>();
            poolGroupUpdateWrapper.eq(PoolGroup::getId, poolGroupInsert.getId())
                    //增加卡片数量
                    .set(PoolGroup::getCNumber, poolGroupInsert.getCNumber() + 1)
                    //增加流量使用
                    .set(PoolGroup::getGroupConsumption, poolGroupInsert.getGroupConsumption() + groupTotal.getConsumption())
                    //流量额度
                    .set(PoolGroup::getQuota, poolGroupInsert.getQuota() + groupTotal.getQuota());
            //提交修改
            poolGroupMapper.update(null, poolGroupUpdateWrapper);
        }
        //当前池成员已经属于该小组了 再去查询客户数量
        //获取该小组现有成员数
        QueryWrapper<GroupTotal> groupTotalWrapper2 = new QueryWrapper<>();
        groupTotalWrapper2.eq("group_name", groupNameInsert)
                .select("DISTINCT customer_name");
        Integer pNumber = groupTotalMapper.selectCount(groupTotalWrapper2);
        //修改小组现有成员数
        //如果跟之前成员数不相同则修改 相同则不修改
        Integer pNumber1 = poolGroupInsert.getPNumber();
        if (!pNumber.equals(pNumber1)) {
            LambdaUpdateWrapper<PoolGroup> poolGroupWrapper2 = new LambdaUpdateWrapper<>();
            poolGroupWrapper2.eq(PoolGroup::getId, poolGroupInsert.getPoolId())
                    .set(PoolGroup::getPNumber, pNumber);
            //提交修改
            poolGroupMapper.update(null, poolGroupWrapper2);

        }
        return AjaxResult.success();
    }


}
